(function () {
    // `ws.readyState`:连接状态：0-未连接；1-已连接；2-正在关闭；3-已关闭
    // `ws.bufferedAmount`:已send()，但尚未发出的信息栈
    window.$ws = {
        open,
        send,
        close,
        readyState,
        onMsg
    }

    /**
     * 连接WS
     */
    async function open(url) {
        return await new Promise((resolve, reject) => {
            if ('WebSocket' in window) {
                let ws = new WebSocket(url);
                // 监听"连接"
                ws.onopen = () => {
                    if (ws.readyState === 1) {
                        resolve(ws);
                    }
                }
                // 监听"错误"
                ws.onerror = () => {
                    reject();
                }
            } else {
                reject();
            }
        })
    }

    /**
     * 向服务器发送
     * @param {Object} ws 连接的WebSocket对象
     * @param {String} method 操作
     * @param {*} data 传输的数据
     */
    async function send(ws, method, data) {
        return await new Promise((resolve, reject) => {
            if (!method || !data) {
                reject();
            }
            let params = {
                method,
                data
            }
            ws.send(JSON.stringify(params));
            ws.onmessage = (e) => {
                resolve(e.data);
            }
        })
    }

    /**
     * 接收服务器信息
     * @param {Object} ws websocket服务器对象
     */
    function onMsg(ws, callback) {
        ws.addEventListener("message", e => {
            callback(JSON.parse(e.data))
        })
        // return
    }

    /**
     * 断开连接
     * @param {Object} ws 连接的WebSocket对象
     */
    async function close(ws) {
        return await new Promise((resolve, reject) => {
            ws.close();
            ws.onclose = () => {
                resolve();
            }
            ws.onerror = () => {
                reject()
            }
        })
    }

    function readyState(ws) {
        return ws.readyState;
    }
})()